﻿/*!
 * Pop (Ajax) à intervalles réguliers, des alarmes :
 *  - Jobs Vtom non associés
 *  - Documents & Graphes expirés
 *
 * L'intervalle est défini (en secondes) dans le fichier de config, variable @Settings.Default.JsonInterval
 */

function alarmes(timeout, urls) {

    function pad(str, max) {
        /// <summary>
        /// Returns a new string of a specified length 
        /// in which the beginning of the current string 
        /// is padded with zeros.
        /// </summary>
        /// <param name="str" type="String">
        /// The string to pad.
        /// </param>
        /// <returns type="String" />

        str = str.toString();
        return str.length < max ? pad("0" + str, max) : str;
    }

    function format(str, params) {
        /// <summary>
        /// Replaces {n} placeholders with arguments.
        /// One or more arguments can be passed, in addition to the string template itself, to insert
        /// into the string.
        /// </summary>
        /// <param name="str" type="String">
        /// The string to format.
        /// </param>
        /// <param name="params" type="String">
        /// The first argument to insert, or an array of Strings to insert
        /// </param>
        /// <returns type="String" />

        if (arguments.length > 2 && params.constructor != Array) {
            params = $.makeArray(arguments).slice(1);
        }
        if (params.constructor != Array) {
            params = [params];
        }
        $.each(params, function (i, n) {
            str = str.replace(new RegExp("\\{" + i + "\\}", "g"), n);
        });
        return str;
    };

    (function recall() {
        $.getJSON(urls.AlarmeJson, function (data) {

            var items = [];
            var span = "<span onclick=\"window.location.href='{0}'\" class=\"ui-button ui-state-error ui-corner-all\" style=\"padding:.3em;\">{1} : {2}</span>";

            items.push(data.expiredDocuments == 0 ? "" :
                format(span, urls.expiredDocuments, "Documents expirés", data.expiredDocuments));

            items.push(data.expiredGraphes == 0 ? "" :
                format(span, urls.expiredGraphes, "Graphes expirés", data.expiredGraphes));

            items.push(data.unreferencedVtoms == 0 ? "" :
                format(span, urls.unreferencedVtoms, "Consignes Vtom non affectées", data.unreferencedVtoms));

            $("#alarms").html(items.join("&nbsp;"));

            var d = new Date();
            var d_ = [
                [d.getDate(), d.getMonth() + 1, d.getFullYear()].join("/"),
                [pad(d.getHours(), 2), pad(d.getMinutes(), 2)].join(":")
            ];

            var r = timeout / 60000;

            $("#clock").html("Alarmes actualisées le <mark>" + d_.join(" à ") + "</mark> &#151; Fréquence : " + r + " mn");

            setTimeout(recall, timeout);
        });
    })();
};